package com.dkm.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dkm.entity.Counselor;
import com.dkm.entity.SignInLog;
import com.dkm.repository.CounselorRepository;
import com.dkm.repository.SignInLogRepository;

@Service
@EnableScheduling //开启定时任务
public class QuartzService {
	//注入签到日志持久层
	@Autowired
	private SignInLogRepository signInLogRepository;
	//注入咨询师持久层
	@Autowired
	private CounselorRepository counselorRepository;
	
	//定时签退
	@Transactional //开启事务
	@Scheduled(cron="59 59 23 * * *")//每天的23:59:59秒执行
	public void sysSignOut() {
		SimpleDateFormat timestampsdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat datesdf=new SimpleDateFormat("yyyy-MM-dd");
		//获取当前年月日
		String currentTime=datesdf.format(new Date());
		System.out.println("=========系统签退["+currentTime+"]=========");
		try {
			Date beigin_time = timestampsdf.parse(currentTime+" 00:00:00");
			Date end_time=timestampsdf.parse(currentTime+" 23:59:59");
			System.out.println(beigin_time);
			System.out.println(end_time);
			//获取今天所有没有签退的日志
			List<SignInLog> signInLogs=signInLogRepository.getSignInLogByCurDay(beigin_time, end_time);
			//签退咨询师
			List<Counselor> counselors=new ArrayList<Counselor>();
			System.out.println("========没有签退的用户========");
			
			if(signInLogs!=null) {
				//遍历获取的日志
				for (SignInLog signInLog : signInLogs) {
					System.out.println("用户编号>"+signInLog.getUser_id());
					//设置签退时间
					signInLog.setSign_out_time(new Date());
					//设置签到状态3:系统签退
					signInLog.setSign_in_status(3);
					
					//根据日志表未签退用户id查询咨询师
					Counselor counselor=counselorRepository.getCounselorByUser_id(signInLog.getUser_id());
					//如果没有签退
					if(counselor!=null&&counselor.getSign_in_state()!=0) {
						//修改状态
						counselor.setSign_in_state(0);
						//加入集合
						counselors.add(counselor);
					}
					
					//根据日志表未签退用户id查询网络咨询师
					Counselor netCounselor=counselorRepository.getNetCounselorByUser_id(signInLog.getUser_id());
					//如果没有签退
					if(netCounselor!=null&&netCounselor.getSign_in_state()!=0) {
						//修改状态
						netCounselor.setSign_in_state(0);
						//加入集合
						counselors.add(netCounselor);
					}
				}
				//批量保存咨询师
				counselorRepository.saveAll(counselors);
				//批量保存日志
				signInLogRepository.saveAll(signInLogs);
			}
			
			System.out.println("===========系统签退完成=============");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("===========系统签退失败=============");
		}
	}
}
